#pragma once
#include <iostream>
#include <pthread.h>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <string>
#include "log.h"
#include <unistd.h>
#include <syscall.h>

// #include <semaphore.h>


namespace sylar{
    class Semaphore{
        private:
            std::mutex _mtx;
            std::condition_variable _cv;
            int _sema;
        public:
            explicit Semaphore(int count = 0):_sema(count)
            {}
            void wait(){ //P操作--
                std::unique_lock<std::mutex> lock(_mtx);
                while(_sema == 0){
                    _cv.wait(lock);
                }
                _sema--;
            }
        
            void signal(){ //V操作++
                std::unique_lock<std::mutex> lock(_mtx);
                _sema++;
                _cv.notify_one();
            }
        };//直接创建一个信号量类ps:也可以直接使用库
        using func_t = std::function<void()>;
        //thread类声明和定义分离
        class Thread{
        
        private:
            pid_t _pid = 0;//进程pid
            pthread_t _tid = 0; //线程tid
            func_t _func;//线程要执行的函数
            std::string _name;
            Semaphore _seamphore;//信号量
        public:
            Thread(std::string name,func_t func);
            ~Thread();
            pid_t getpid() const{
                return _pid;
            }
            const std::string getname() const{
                return _name;
            }
            void join();
        public:
            static pid_t getnowtid(); //获取当前线程tid(系统层面)
            static Thread* getnowthreadp(); //获取当前线程指针
            // 获取当前线程的名字
            static const std::string& getnowname();
            // 设置当前线程的名字
            static void setnowname(const std::string& name);
        private:
            static void* run(void* arg);
        
        };
}